<template>
  <div>
    <!-- 按钮 -->
    <el-button
      type="primary"
      icon="el-icon-plus"
      style="margin-bottom: 10px"
      @click="showDidlog"
      >添加</el-button
    >

    <!-- 点击添加对话框 -->
    <el-dialog title="添加品牌" :visible.sync="dialogFormVisible">
      <!--
         Form 组件提供了表单验证的功能，只需要通过 rules 属性传入约定的验证规则，
         并将 Form-Item 的 prop 属性设置为需校验的字段名即可。 
      -->
      <el-form
        style="width: 80%"
        :model="tmForm"
        :rules="rules"
        ref="rulesForm"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmForm.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- action: 设置图片上传的地址
          :on-success: 可以检测图片上传成功，当图片上传成功会执行一次
          :before-upload: 可以在图片上传之前执行一次
           -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件, 且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 表格 -->
    <el-table border style="width: 100%" :data="list">
      <el-table-column type="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column>
      <el-table-column prop="logoUrl" label="品牌logo" width="width">
        <template slot-scope="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template slot-scope="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="updateTradeMark(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteTradeMark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin-top: 20px; text-align: center"
      :current-page="page"
      :page-size="limit"
      :page-sizes="[3, 5, 7]"
      :page-count="7"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="prev, pager, next, jumper, ->, sizes, total"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  name: "TradeMark",
  data() {
    return {
      page: 1, //代表当前第几页
      limit: 5, //当前展示数据条数
      total: 0,
      list: [],
      dialogFormVisible: false, //对话框显示与影藏
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "change",
          },
        ],
        logoUrl: [{ required: true, message: "请输入选择品牌图片" }],
      },
    };
  },
  mounted() {
    //获取品牌列表数据
    this.getPageList();
  },
  methods: {
    //获取品牌列表数据
    async getPageList() {
      const { page, limit } = this;
      const res = await this.$API.tradeMark.reqTradeMarkList(page, limit);
      // console.log(res);
      if (res.code === 200) {
        this.total = res.data.total;
        this.list = res.data.records;
      }
    },
    handleCurrentChange(pager) {
      // console.log(pager);
      this.page = pager;
      this.getPageList();
    },
    handleSizeChange(limit) {
      // console.log(limit);
      this.limit = limit;
      this.getPageList();
    },
    //点击添加品牌按钮
    showDidlog() {
      this.dialogFormVisible = true;
      this.tmForm = { tmName: "", logoUrl: "" };
    },
    //点击修改品牌按钮
    updateTradeMark(row) {
      this.dialogFormVisible = true;
      this.tmForm = { ...row }
    },
    //图片上传成功
    handleAvatarSuccess(res, file) {
      // console.log(res);
      // console.log(file);
      // res: 上传成功之后返回前端数据
      // file: 上传成功之后服务器返回前端数据
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.tmForm.logoUrl = res.data;
    },
    //图片上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //添加or修改确定按钮
    addOrUpdateTradeMark() {
      this.$refs.rulesForm.validate(async (success) => {
        //如果验证成功
        if (success) {
          this.dialogFormVisible = false;
          let res = await this.$API.tradeMark.reqAddOrupdateTradeMark(
            this.tmForm
          );
          // console.log(res);
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: this.tmForm.id ? "修改品牌成功" : "添加品牌成功",
            });
            this.getPageList(this.tmForm.id ? this.page : 1);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除按钮点击事件
    deleteTradeMark(row) {
      // console.log(row);
      this.$confirm(`你确定删除${row.tmName}吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //当用户点击确定按钮时触发
          //向服务器发送请求
          this.$API.tradeMark.reqDeleteTradeMark(row.id).then((res) => {
            // console.log(res);
            //如果删除成功
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getPageList(this.list.length > 1 ? this.page : this.page - 1);
            }
          });
        })
        .catch(() => {
          //当用户点击取消按钮时触发
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>